﻿using System.Linq.Expressions;
using BabyShop.Site.Exts.Extensions;

namespace BabyShop.Site.Data.Conventions.Properties
{
    public class StringContainsConvention : PropertyExpressionConventionBase
    {

        public StringContainsConvention() : base(10) { }

        public override Expression BuildExpression(BuildPropertyExpressionContext context) {
            if (context.Property.PropertyType != typeof(string)) return null;

            var queryValue = context.ValueProvider.GetQueryValue(context.Property.Name, context.Property.PropertyType);
            context.ModelState.AddIfValueNotNull(context.Property.Name, queryValue.ModelState);
            context.IsHandled = queryValue.ModelState != null;

            return (queryValue.Value as string).IsNullOrEmpty()
                       ? null
                       : context.PropertyExpression.Call("Contains", Expression.Constant(queryValue.Value));
        }
    }
}